var app = getApp();

var api = require("./api.js");

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
	return new Promise(function(resolve, reject) {
		wx.request({
			url: url,
			data: data,
			method: method,
			header: {
				"Content-Type": "application/json"
			}, // 设置请求的 header
			success: function(res) {
				resolve(res);
			},
			fail: function() {
				reject(res);
			}
		});
	});
}

/**
 * 获取用户openid
 */
function getOpenId() {
	return new Promise(function(resolve, reject) {
		wx.login({
			success: res => {
				// 发送 res.code 到后台换取 openId
				var url =
					"https://api.weixin.qq.com/sns/jscode2session?appid=" +
					app.globalData.appid +
					"&secret=" +
					app.globalData.secret +
					"&js_code=" +
					res.code +
					"&grant_type=authorization_code";
				wx.request({
					url: url,
					data: {},
					method: "GET",
					success: function(res) {
						resolve(res.data.openid);
					}
				});
			}
		});
	});
}

/**
 *获取当前时间
 */
function getNowFormatDate() {
	var date = new Date();
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentdate =
		date.getFullYear() +
		seperator1 +
		month +
		seperator1 +
		strDate +
		" " +
		date.getHours() +
		seperator2 +
		date.getMinutes() +
		seperator2 +
		date.getSeconds();
	return currentdate;
}

module.exports = {
	getOpenId: getOpenId,
	request: request,
	getNowFormatDate: getNowFormatDate
};
